<?php
namespace Home\Model;

use  Think\Model;

class OrdersModel extends Model
{
  protected $autoCheckFields =false;

  public function create_tran_no()
  {
    $now_time = gmtime();
    $tran_no = date("YmdHis", $now_time).random(4, 1);

    return $tran_no;
  }

  //加/减库存 type=1减库存type=2加库存
  public function change_stock($order_id, $type=1)
  {
    $exp = "-";
    if ($type==2) {
      $exp = "+";
    }
    //商品列表
    $field = "id,product_name,product_price,product_num,product_id,product_spec";
    $child_list = M("order_children")->field($field)->where("order_id=".$order_id)->order("id asc")->select();
    foreach ($child_list as $key => $value) {
      $update_data = array();
      $update_data['stock'] = array('exp',"stock".$exp.$value['product_num']);
      $result = M("products")->where("id=".$value['product_id'])->save($update_data);
    }

    return $result;
  }

  public function check_coupon($user_coupon_id, $shop_id, $user_id)
  {
    //商品列表
    $result = array('success' => false);
    $user_coupon_map = array(
      'id' => $user_coupon_id,
      'user_id' => $user_id);

    $user_coupon = M('user_coupons')->where($user_coupon_map)->find();

    $result['user_coupon'] = $user_coupon;
    if (!$user_coupon) {
      $result['msg'] = "check_coupon.user_coupon_id.error";
    }

    if ($user_coupon['status'] == 1) {
      $coupon_map = array(
        'id' => $user_coupon['coupon_id'],
        'shop_id' => $shop_id);

      $coupon = M('coupons')->where($coupon_map)->find();
      $result['coupon'] = $coupon;
    } else {
      $result['msg']= "check_coupon.user_coupon.status.error";
    }

    if (!$coupon) {
      $result['msg']= "this coupon is not in this shop";
    }

    $current_time = date("Y-m-d H:i:s", gmtime());
    if ($coupon['status'] == 2 && $coupon['expired_at'] >= $current_time && $coupon['activated_at'] <= $current_time) {
      $result['msg'] = "check_coupon.success";

      $result['success'] = true;
    } else {
      $result['msg']= "check_coupon.coupon.invalid";
    }
    
    return $result;
  }
}
